﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewMaker;

namespace HDInsightStudio
{
    public abstract class TreeItem : ViewModelBase
    {
        public abstract string Name { get; }

        public bool IsSelected
        {
            get { return _isSelected; }
            set { _isSelected = value; OnPropertyChanged("IsSelected"); }
        }
        private bool _isSelected;


        public bool IsExpanded
        {
            get { return _isExpanded; }
            set { _isExpanded = value; OnPropertyChanged("IsExpanded"); }
        }
        private bool _isExpanded;

        [Browsable(false)]
        public virtual ObservableCollection<TreeItem> Children
        {
            get
            {
                if (_children == null) _children = new ObservableCollection<TreeItem>();
                return _children;
            }
        }
        private ObservableCollection<TreeItem> _children; 

        public TreeItem Parent { get; private set; }

        public TreeItem(TreeItem parent)
        {
            this.Parent = parent;
        }

        public TreeItem FindNode(string findStr, bool childOnly = false)
        {
            if (!childOnly && this.Parent != null && Parent.Children.IndexOf(this) < Parent.Children.Count - 1)
            {
                foreach (var item in Parent.Children.SkipWhile(x => x != this).Skip(1))
                {
                    if (item.Name.ToLower().Contains(findStr.ToLower()))
                    {
                        item.IsSelected = true;
                        return item;
                    }
                }
            }
            foreach (var child in this.Children)
            {
                if (child.Name.ToLower().Contains(findStr.ToLower()))
                {
                    child.IsSelected = true;
                    this.IsExpanded = true;
                    return child;
                }
            }
            foreach (var child in Children)
            {
                var result = child.FindNode(findStr, true);
                if (result != null)
                {
                    this.IsExpanded = true;
                    return result;
                }
            }
            if (!childOnly && this.Parent != null && Parent.Children.IndexOf(this) < Parent.Children.Count - 1)
            {
                foreach (var item in Parent.Children.SkipWhile(x => x != this).Skip(1))
                {
                    var result = item.FindNode(findStr, true);
                    if (result != null)
                    {
                        this.IsExpanded = true;
                        return result;
                    }
                }
            }
            return null;
        }

    }

}
